package com.fau.mm.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;

import com.fau.mm.service.BaseAllService;
import com.fau.mm.util.Page;
import com.opensymphony.xwork2.ActionSupport;

/**
 * @desc 控制层公共类,继承ActionSupport类,提供控制层公共属性及方法
 * @author liny
 * @datetime 2014年7月30日 上午10:03:35
 */
@Controller
public class PublicAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(PublicAction.class);
	
	@Resource
	protected BaseAllService baseAllService;
	protected Page pageBean;
	protected Map<String, Object> map;
	protected List<?> list;

	/**
	 * @desc map转换成json对象，返回请求页面
	 * @param response
	 * @param map
	 * @author liny
	 * @datetime 2014年7月30日 上午10:10:18
	 */
	@SuppressWarnings({ "unchecked" })
	public void formatJSON(HttpServletResponse response,Map<String,Object> map) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			JSONObject obj = new JSONObject();
			Set<String> mapSet = map.keySet();
			for(Iterator<String> it=mapSet.iterator();it.hasNext();){
				String key = it.next();
				obj.put(key, map.get(key));
			}
			out.print(obj.toJSONString());
			log.info(obj.toJSONString());
		} catch (IOException e) {
			log.error(e.getMessage());
		} finally {
			out.flush();
			out.close();
		}
	}
	
	/**
	 * @desc list转换成json数组对象,返回请求页面
	 * @param response
	 * @param list
	 * @author liny
	 * @datetime 2014年7月30日 上午10:14:20
	 */
	@SuppressWarnings("unchecked")
	public void formatJSON(HttpServletResponse response,List<?> list) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			JSONArray obj = new JSONArray();
			obj.addAll(list);
			out.print(obj.toJSONString());
			log.info(obj.toJSONString());
		} catch (IOException e) {
			log.error(e.getMessage());
		} finally {
			out.flush();
			out.close();
		}
	}
	
	/**
	 * @desc 上传方法
	 * @param request
	 * @param response
	 * @param extType
	 * @param maxsize
	 * @return String
	 * @author liny
	 * @datetime 2014年7月30日 下午2:15:24
	 */
	public String uploadFile(HttpServletRequest request, HttpServletResponse response, final String extType, long maxsize) {
		response.setContentType("text/html;charset=UTF-8");
		
		FileOutputStream fos = null;
		InputStream is = null;
		
		String savePath = ServletActionContext.getServletContext().getRealPath("upload");
		String saveURL = request.getContextPath()+"/upload";
		
		
		File uploadDir = new File(savePath);
		if(!uploadDir.isDirectory()){
			return "上传目录不存在";
		}
		
		if(!uploadDir.canWrite()){
			return "上传目录没有写权限";
		}
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += File.separator + ymd + File.separator;
		saveURL += "/" + ymd + "/";
		
		File dirFile = new File(savePath);
		if(!dirFile.exists()){
			dirFile.mkdirs();
		}
		
		MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
		String fileName = wrapper.getFileNames("Filedata")[0];
		File srcFile = wrapper.getFiles("Filedata")[0];
		String fileExt = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
		
		if(!extType.contains(fileExt)){
			return "上传文件扩展名是不允许的扩展名";
		}
		
		if(maxsize < srcFile.length()){
			return "上传文件过大，请重新上传";
		}
		
		sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String newFileName = sdf.format(new Date())+"_"+new Random().nextInt(1000)+"."+fileExt;
		byte[] buffer = new byte[1024];
		try {
			is = new FileInputStream(srcFile);
			fos = new FileOutputStream(savePath + newFileName);
			int num = 0;
			while((num = is.read(buffer)) > 0){
				fos.write(buffer,0,num);
			}
		} catch (IOException e) {
			log.error(e.getMessage());
		} finally {
			try {
				is.close();
				fos.close();
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
		
		return saveURL + newFileName;
	}
	
	/**
	 * @desc 获取上传文件流
	 * @param request 请求
	 * @param response 响应
	 * @return
	 * @author kangyj
	 * @datetime 2014年10月22日,上午12:29:07
	 */
	public File getImportFile(HttpServletRequest request, HttpServletResponse response){
		response.setContentType("text/html;charset=UTF-8");
		MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
		File file = wrapper.getFiles("Filedata")[0];
		return file;
	}

}
